package xyz.ranyh.jobclient.fragment;

import android.app.ListFragment;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import xyz.ranyh.jobclient.R;
import xyz.ranyh.jobclient.http.GetJobsListTask;
import xyz.ranyh.jobclient.http.Url;
import xyz.ranyh.jobclient.util.JobBean;
import xyz.ranyh.jobclient.util.JobsListAdapter;

/**
 * A simple {@link ListFragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link JobListFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link JobListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class JobListFragment extends ListFragment {
    private GetJobsListTask getJobsListTask;
    private ArrayList<JobBean> jobs = new ArrayList<JobBean>();;
    private JobsListAdapter jobsListAdapter;
    private WebView webView;
    private WebViewListener webViewListener;
    private SwipeRefreshLayout swipeRefreshLayout;
    private TextView loadmoreBtn;
    private String nextPageUrl;
    private String keyword;
    private ActionBar actionBar;
    private Button searchButton;
    private EditText searchEdit;
    private Button cancelButton;

    public WebViewListener getWebViewListener() {
        return webViewListener;
    }

    public void setWebViewListener(WebViewListener webViewListener) {
        this.webViewListener = webViewListener;
    }

    public interface WebViewListener {
        void initWebView(String url, String title);
    }

    private OnFragmentInteractionListener mListener;

    public JobListFragment() {
    }

    public void setActionBar(ActionBar actionBar) {
        this.actionBar = actionBar;
    }
    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment JobListFragment.
     */
    public static JobListFragment newInstance() {
        JobListFragment fragment = new JobListFragment();

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        jobsListAdapter = new JobsListAdapter(getActivity(), jobs);
        getJobList();
        jobsListAdapter.setListener(new JobsListAdapter.ViewClickListener() {
            @Override
            public void onClick(int i, View view, String url) {
                String title = jobs.get(i).getTitle();
                webViewListener.initWebView(url, title);
            }

            @Override
            public void loadmoreListener() {
                Log.d("load more", "loadmoreListener: ");
                loadMore();
                swipeRefreshLayout.setPadding(0, 0, 0, 120);
                loadmoreBtn = (TextView) getActivity().findViewById(R.id.loadmore);
                loadmoreBtn.setVisibility(View.VISIBLE);
            }

            @Override
            public void hideLoadmore() {
                swipeRefreshLayout.setPadding(0, 0, 0, 0);
                loadmoreBtn = (TextView) getActivity().findViewById(R.id.loadmore);
                loadmoreBtn.setVisibility(View.INVISIBLE);

            }
        });
        this.setListAdapter(jobsListAdapter);
        searchButton = (Button) actionBar.getCustomView().findViewById(R.id.search_button);
        searchEdit = (EditText) actionBar.getCustomView().findViewById(R.id.search_edit);
        cancelButton = (Button) actionBar.getCustomView().findViewById(R.id.cancel_button);

        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                keyword = searchEdit.getText().toString();
                getSearchJobList();
            }
        });

        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
            }
        });
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.search_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM|ActionBar.DISPLAY_SHOW_HOME);
        return true;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_job_list, container, false);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        return view;
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);

    }

    private void getJobList() {
        _getJobList(Url.JOBS_URL);
    }

    private void getSearchJobList() {
        jobs.clear();
        jobsListAdapter.notifyDataSetChanged();
        String url = Url.JOBS_URL+"?s="+keyword;
        _getJobList(url);
    }

    private void _getJobList(String url) {
        getJobsListTask = new GetJobsListTask(url, jobs, jobsListAdapter);

        jobsListAdapter.setJobs(jobs);
        getJobsListTask.setGetJoblistener(new GetJobsListTask.GetJoblistener() {
            @Override
            public void onSuccess(JSONObject res) {
                JSONArray jobList = null;
                try {
                    jobList = res.getJSONArray("jobs");
                    nextPageUrl=res.getString("next");
                    Log.d("next", nextPageUrl);
                    for (int i = 0; i < jobList.length(); i++) {
                        JSONObject item = (JSONObject) jobList.get(i);

                        JobBean mJB = new JobBean();
                        mJB.setId(item.getInt("id"));
                        mJB.setTitle(item.getString("title"));
                        mJB.setUrl(item.getString("url"));
                        mJB.setRefUrl(item.getString("ref_url"));
                        mJB.setTags(item.getString("tags"));
                        mJB.setFollowerCount(item.getInt("follower_count"));
                        mJB.setOpenDate(item.getString("open_date"));
                        mJB.setPublishedDate(item.getString("published_date"));
                        mJB.setOpenDateInt(item.getInt("open_date_int"));

                        jobsListAdapter.add(mJB);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (jobs.size() > 0 && swipeRefreshLayout.isRefreshing()) {
                    Toast.makeText(getActivity(), "刷新成功", Toast.LENGTH_SHORT).show();
                }
                swipeRefreshLayout.setRefreshing(false);
            }
        });
        getJobsListTask.execute();
    }

    private void refresh() {
        jobs = new ArrayList<JobBean>();
        getJobList();
    }

    private void loadMore() {
        getJobsListTask = new GetJobsListTask(nextPageUrl, jobs, jobsListAdapter);
        getJobsListTask.setGetJoblistener(new GetJobsListTask.GetJoblistener() {
            @Override
            public void onSuccess(JSONObject res) {
                JSONArray jobList = null;
                try {
                    jobList = res.getJSONArray("jobs");

                    for (int i = 0; i < jobList.length(); i++) {
                        JSONObject item = (JSONObject) jobList.get(i);

                        JobBean mJB = new JobBean();
                        mJB.setId(item.getInt("id"));
                        mJB.setTitle(item.getString("title"));
                        mJB.setUrl(item.getString("url"));
                        mJB.setRefUrl(item.getString("ref_url"));
                        mJB.setTags(item.getString("tags"));
                        mJB.setFollowerCount(item.getInt("follower_count"));
                        mJB.setOpenDate(item.getString("open_date"));
                        mJB.setPublishedDate(item.getString("published_date"));
                        mJB.setOpenDateInt(item.getInt("open_date_int"));

                        jobsListAdapter.add(mJB);
                    }
                    Log.d("sss", String.valueOf(jobs.size()));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (jobs.size() > 0 && swipeRefreshLayout.isRefreshing()) {
                    Toast.makeText(getActivity(), "刷新成功", Toast.LENGTH_SHORT).show();
                }
                swipeRefreshLayout.setPadding(0,0,0,0);
                loadmoreBtn.setVisibility(View.INVISIBLE);
                swipeRefreshLayout.setRefreshing(false);
                getJobsListTask.cancel(true);
                try {
                    nextPageUrl=res.getString("next");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        getJobsListTask.execute();
    }
}
